import {Form, Row, Col, Input, Select, InputNumber, message, Space, Button, Upload, Drawer, Divider} from 'antd';
import {useEffect, useState} from 'react';
import {connect} from 'umi';
import {normFile, beforeUpload, uuid} from "@/utils/upload";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import BraftEditor from "braft-editor";
import 'braft-editor/dist/index.css';
import {uploadFn} from "@/utils/upload";
import {host} from "@/requestErrorConfig";
import {controls} from "@/utils/const";

const DataForm = (props) => {
  const {dispatch, submitting} = props;
  const {dataForm, setDataForm, tablePayload, setTablePayload, selectedId} = props.data;
  const [form] = Form.useForm();
  const [editorState, setEditorState] = useState(null);
  const [cover, setCover] = useState([]);
  const [coverUploading, setCoverUploading] = useState(false);
  const [video, setVideo] = useState([]);
  const [videoUploading, setVideoUploading] = useState(false);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({status: 1, orderby: 0});
    }
    if (dataForm && dataForm.data) {
      let cover_ = [];
      if (dataForm.data.cover) {
        cover_ = [{uuid: uuid(), name: dataForm.data.cover.split("/").pop(), status: 'done', url: dataForm.data.cover}];
      }
      setCover(cover_)

      let video_ = [];
      if (dataForm.data.video) {
        video_ = [{uuid: uuid(), name: dataForm.data.video.split("/").pop(), status: 'done', url: dataForm.data.video}];
      }
      setVideo(video_)

      form.setFieldsValue({
        ...dataForm.data,
        cover: cover_,
        video: video_,
        detail: BraftEditor.createEditorState(dataForm.data.detail)
      });
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      values.placeId = selectedId;
      if (values.placeId <= 0) {
        message.error('请选择推荐位').then();
        return;
      }

      values.detail = editorState ? editorState.toHTML() : '';

      if (values.cover && values.cover.length > 0) {
        let cover = values.cover.pop();
        if (cover.status === 'done') {
          values.cover = cover.url;
        }
      } else {
        values.cover = "";
      }

      if (values.video && values.video.length > 0) {
        let video = values.video.pop();
        if (video.status === 'done') {
          values.video = video.url;
        }
      } else {
        values.video = "";
      }

      dispatch({
        type: values.id ? 'PCmsPlaceRight/edit' : 'PCmsPlaceRight/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setCover([]);
    setVideo([]);
    setEditorState(null);
    setDataForm(undefined);
    form.resetFields();
  }

  /* 上传监听 */
  const handleChange = (info, field) => {
    if (field === 'cover') {
      setCover(info.fileList);
    }
    if (field === 'video') {
      setVideo(info.fileList);
    }

    if (info.file.status === 'uploading') {
      if (field === 'cover') {
        setCoverUploading(true);
      }
      if (field === 'video') {
        setVideoUploading(true);
      }
      return;
    }

    if (info.file.status === 'done') {
      setCoverUploading(false);
      setVideoUploading(false)
      let response = {...info.file.response};
      if (response.code !== 0) {
        info.file.status = 'error';
        info.file.response = '上传失败';
      } else {
        info.file.uid = response.data.url;
        info.file.name = response.data.name;
        info.file.status = 'done';
        info.file.url = response.data.url;
      }
    }
  };

  return (
    <Drawer
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onClose={onCancel}
      forceRender={true}
      width={1300}
      headerStyle={{padding: '8px 24px'}}
      bodyStyle={{paddingBottom: 80}}
      extra={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button loading={submitting} onClick={onOk} type="primary">提交</Button>
        </Space>
      }
    >
      <Form layout='horizontal' labelCol={{span: 6}} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='title' label='标题'
              rules={[
                {required: true, message: '标题不能为空'},
              ]}>
              <Input placeholder='请输入标题'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='tag' label='标签'
              rules={[
                {required: false, message: '标签不能为空'},
              ]}>
              <Input placeholder='请输入标签'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='rawUrl' label='链接'
              rules={[
                {required: false, message: '链接不能为空'},
              ]}>
              <Input placeholder='请输入链接'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='param' label='参数'
              rules={[
                {required: false, message: '参数不能为空'},
              ]}>
              <Input placeholder='请输入参数'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='outUrl' label='外链'
              rules={[
                {required: false, message: '外链不能为空'},
              ]}>
              <Input placeholder='请输入外链'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='metadata' label='元数据'
              rules={[
                {required: false, message: '元数据不能为空'},
              ]}>
              <Input placeholder='请输入元数据'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='status' label='当前状态'
              rules={[
                {required: true, message: '当前状态不能为空'},
              ]}
            >
              <Select placeholder='请选择当前状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='orderby' label='排序属性'
              rules={[
                {required: true, message: '排序属性不能为空'},
              ]}>
              <InputNumber style={{width: '100%'}} placeholder='请输入排序属性'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              labelCol={{span: 6}}
              name='description' label='描述'
              rules={[
                {required: false, message: '描述不能为空'},
              ]}>
              <Input.TextArea rows={3} placeholder='推荐位描述'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              labelCol={{span: 6}}
              name='remark' label='备注信息'
              rules={[
                {required: false, message: '备注信息不能为空'},
              ]}
            >
              <Input.TextArea rows={3} placeholder='请输入备注信息'/>
            </Form.Item>
          </Col>
        </Row>
        <Divider style={{marginTop: 0}}/>
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item
              labelCol={{span: 12}}
              name={'cover'}
              label="封面图"
              valuePropName="fileList" getValueFromEvent={normFile}>
              <Upload
                name="file" action={`${host}/minio/upload`}
                headers={{tenantToken: window.localStorage.getItem('token')}}
                beforeUpload={(file) => beforeUpload(file, 10)}
                onChange={(info) => handleChange(info, 'cover')}
                accept={'image/*'} listType="picture-card">
                {(!cover || cover.length < 1) && (
                  <div>
                    {coverUploading ? <LoadingOutlined/> : <PlusOutlined/>}
                    <div
                      style={{
                        marginTop: 8,
                      }}
                    >
                      上传图片
                    </div>
                  </div>
                )}
              </Upload>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              labelCol={{span: 12}}
              name={'video'}
              label="视频"
              valuePropName="fileList" getValueFromEvent={normFile}>
              <Upload
                name="file" action={`${host}/minio/upload`}
                headers={{tenantToken: window.localStorage.getItem('token')}}
                beforeUpload={(file) => beforeUpload(file, 50)}
                onChange={(info) => handleChange(info, 'video')}
                accept={'video/*'} listType="picture-card">
                {(!video || video.length < 1) && (
                  <div>
                    {videoUploading ? <LoadingOutlined/> : <PlusOutlined/>}
                    <div
                      style={{
                        marginTop: 8,
                      }}
                    >
                      上传视频
                    </div>
                  </div>
                )}
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <Divider style={{marginTop: -8}}/>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{span: 3}}
              name='detail' label='详情'
              rules={[
                {required: false, message: '详情不能为空'},
              ]}>
              <BraftEditor
                controls={controls}
                style={{border: '1px solid #ddd', borderRadius: 4}}
                media={{uploadFn, accepts: {audio: false}}}
                onChange={e => setEditorState(e)}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};


export default connect(({loading, PCmsPlaceLeft}) => {
  return {
    submitting: loading.effects['PCmsPlaceRight/add'] || loading.effects['PCmsPlaceRight/edit'],
    placeList: PCmsPlaceLeft.list,
  };
})(DataForm);

